package com.blog.sorket.dao;

import com.blog.sorket.pojo.Message;
import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.List;

@Component
public class MessageDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 查询点对点聊天记录
     *
     * @param fromId
     * @param toId
     * @param page
     * @param rows
     * @return
     */
    public List<Message> findListByFromAndTo(String fromId, String toId, Integer page, Integer rows) {
        // 用户a发送给用户b的条件
        Criteria criteriaFrom = new Criteria().andOperator(
                Criteria.where("from.id").is(fromId),
                Criteria.where("to.id").is(toId)
        );
        // 用户b发送给用户a的条件
        Criteria criteriaTo = new Criteria().andOperator(
                Criteria.where("from.id").is(toId),
                Criteria.where("to.id").is(fromId)
        );

        Criteria criteria = new Criteria().orOperator(criteriaFrom, criteriaTo);
        // 设置查询条件， 分页，升序
        PageRequest pageRequest = PageRequest.of(page-1,rows, Sort.by(Sort.Direction.ASC, "sendDate"));
        Query query = Query.query(criteria).with(pageRequest);
        return this.mongoTemplate.find(query, Message.class);
    }

    /**
     * 根据id查询数据
     *
     * @param id
     * @return
     */
    public Message findMessageById(String id) {

        return null;
    }

    /**
     * 更新消息状态
     *
     * @param id
     * @param status
     * @return
     */
    public UpdateResult updateMessageState(String id, Integer status) {
        return null;
    }

    public Message saveMessage(Message message) {
        // 写入发送时间
        message.setId(ObjectId.get().toString());
        message.setSendDate(new Date());
        message.setStatus(1);// 未读
        return this.mongoTemplate.save(message);
    }

    /**
     * 根据消息id删除数据
     *
     * @param id
     * @return
     */
    public DeleteResult deleteMessage(String id) {
        return null;
    }
}
